package com.github.rpc4j.consumer.spring;

import org.springframework.beans.factory.FactoryBean;

import com.github.rpc4j.common.ServiceRequest;
import com.github.rpc4j.consumer.asm.ClassDump;
import com.github.rpc4j.consumer.core.ConsumerExecuteHandler;
import com.github.rpc4j.consumer.core.DefaultExecuteHandler;
import com.github.rpc4j.consumer.core.Rpc4jConsumerService;

public class Rpc4jSpringConsumerBean implements FactoryBean {

	private String interfaceName;

	private String version;

	private Object target;

	private Rpc4jConsumerService consumerService;

	public void setInterfaceName(String interfaceName) {
		this.interfaceName = interfaceName;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public void setConsumerService(Rpc4jConsumerService consumerService) {
		this.consumerService = consumerService;
	}

	public void init() throws Exception {
		ServiceRequest request = new ServiceRequest();
		request.setInterfaceName(interfaceName);
		request.setVersion(version);
		ClassDump<Object> dump = new ClassDump<Object>();
		ConsumerExecuteHandler handler = new DefaultExecuteHandler(consumerService.getContext());
		target = dump.getObject(handler,request);
	}

	@Override
	public Object getObject() throws Exception {
		return target;
	}

	@Override
	public Class getObjectType() {
		return target.getClass();
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

}
